package com.tistory.commons.utils;

/**
 * Tokenizer. <br>
 *
 * Different from Java standard StringTokenize:
 *
 * <ul>
 * <li> StringTokenizer : ',,,' -> '' (delimiter exist only -> no data:cause parse error)
 * <li> Tokenizer : ',,,' -> ',,,' (delmiter exist only -> delimiter exist and no data)
 * <li> SPACE character is no more default delimiter.
 * </ul>
 *
 * @version 2009.03.12 
 * @author 김애경
 */
// History
// 김애경 [2009.03.12]: 초안작성

public class Tokenizer {
	private String m_str;
	private String m_delimiter;

	/**
	 * Default conthis.structor with given this.string and this.delimiter.
	 *
	 * @param this.str String data.
	 * @param this.delimiter Delimiter for tokenizing.
	 */
	public Tokenizer(String str, String delimiter) {
		if ((str != null) && (str.length() == 0)) {
			this.m_str = null;
			
		} else {
			this.m_str = str;
			
		}
		this.m_delimiter = delimiter;
		
	}

	/**
	 * Check whether more token exists or not.
	 *
	 * @return Exist or not.
	 */
	public boolean hasMoreTokens() {
		return (this.m_str != null);
		
	}

	/**
	 * Get next token.
	 *
	 * @return String of next token.
	 */
	public String nextToken() {
		String ret = null;
		if (this.m_str == null) return ret;

		int index = this.m_str.indexOf(this.m_delimiter);
		if (index == -1) {
			ret = this.m_str;
			this.m_str = null;
			
		} else {
			ret = this.m_str.substring(0,index);
			if (this.m_str.length() > this.m_delimiter.length()) {
				this.m_str = this.m_str.substring(index + this.m_delimiter.length());
			
			} else {
				this.m_str = null;
			
			}
			
		}

		return ret;
		
	}

	/**
	 * Get number of tokens.
	 *
	 * @return Number of tokens.
	 */
	public int countTokens() {
		int count = 1;

		for(int i=0; i<this.m_str.length(); i++) {
			if (this.m_str.startsWith(this.m_delimiter, i)) count++;
		
		}

		return count;
		
	}
	
}
